package com.cqust.icc.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

import static com.cqust.icc.aspect.AddLog.extracted;

/**
 * @author 张成
 * @version 1.0
 * @date 2022/3/31 15:33
 */

@Component
@Aspect
public class LogAspect {

    @Pointcut("@annotation(com.cqust.icc.aspect.Log)")
    public void pointcut() {
    }

    @AfterReturning(pointcut = "pointcut()", returning = "jsonResponse")
    public void doReturningLogRecord(JoinPoint joinPoint, Object jsonResponse) {
        recordLog(joinPoint, jsonResponse);
    }

    @AfterThrowing(value = "pointcut()")
    public void doThrowingLogRecord(JoinPoint joinPoint) {
        recordLog(joinPoint, null);
    }

    private void recordLog(JoinPoint joinPoint, Object jsonResponse) {
        System.out.println(jsonResponse);
        Log log = getAnnotation(joinPoint);

        if (log == null) {
            return;
        }

        extracted(log.moduleName());
        //TODO: 记录日志的具体逻辑 如：获取各种信息，写入数据库等操作...

    }

    /**
     * 通过反射获取注解
     */
    private Log getAnnotation(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }

}

